'''
v1.01 2018-02-06 first commint.
'''

import random

#flag for judge whether achive 2048
WinFlag = 0
#marco for table widith number
WIDTH_VALUE = 4
#marco for table heigth number
HEIGTH_VALUE = 4

#main table
view =[ [0, 0, 0, 0],
        [0, 0, 0, 0],  
        [0, 0, 0, 0],  
        [0, 0, 0, 0]]  

#temp table for operation 'up' and 'down'
exchange =[ [0, 0, 0, 0],
            [0, 0, 0, 0],  
            [0, 0, 0, 0],  
            [0, 0, 0, 0]] 

#show main table
def display():
        print('=======================')
        print('{0:4} {1:4} {2:4} {3:4}'.format(view[0][0], view[0][1], view[0][2], view[0][3]))  
        print('{0:4} {1:4} {2:4} {3:4}'.format(view[1][0], view[1][1], view[1][2], view[1][3]))  
        print('{0:4} {1:4} {2:4} {3:4}'.format(view[2][0], view[2][1], view[2][2], view[2][3]))  
        print('{0:4} {1:4} {2:4} {3:4}'.format(view[3][0], view[3][1], view[3][2], view[3][3]))
        print('=======================')

#init
def init():
    #gene random value for main table
    for count in range(HEIGTH_VALUE):
        view[count] = random.sample([0,0,0,0,2,2,4],WIDTH_VALUE)

#del zero
def move(rowList,dct):
    #delete zero row by row
    for count in range(rowList.count(0)):
        rowList.remove(0)
    
    #create zero list
    zeroList = [0]*(WIDTH_VALUE - len(rowList))
    
    #extend zero
    if dct == 'left':  
        rowList.extend(zeroList)  
    else:  
        rowList[:0] = zeroList  

#add same value
def add(rowList,dct):
    if(dct == 'left'):
        for lcount in [0, 1, 2]:
            if(rowList[lcount] == rowList[lcount+1] != 0):
                rowList[lcount] *= 2
                rowList[lcount+1] = 0
    else:
        for count in [3, 2, 1]:  
            if(rowList[count] == rowList[count-1] != 0):  
                rowList[count-1] *= 2  
                rowList[count] = 0

    return {'result':0}    
            

def control(rowList,dct):
    #delete zero,create new view table by direction
    move(rowList,dct)
    #add same value by direction
    res = add(rowList,dct)
    #create new view again
    if(res['result'] == 0):
        move(rowList,dct)

#random gene new value
def gene(viewList):
    emptyNum = 0
    loopCount = 0
    randCount = 0

    #get zero total count
    for rowCount in range(0,HEIGTH_VALUE):
        loopCount += viewList[rowCount].count(0)

    #gene a random zero index
    if(loopCount > 1):
        randCount = random.randrange(1,loopCount)
    else:
        randCount = 1

    #gene a random value
    randValue = random.choice([2, 2, 2, 4])

    #search list,match the random zero index and list zero index
    for rowCount in range(0,HEIGTH_VALUE):
        for colCount in range(0,WIDTH_VALUE):
            if(viewList[rowCount][colCount] == 0):
                emptyNum+=1
                if(randCount == emptyNum):
                    viewList[rowCount][colCount] = randValue

    #if there aren't empty area,game over
    if (emptyNum==0):
        return -1

    return 0

def isFinsh(viewList):
    global WinFlag
    for rowCount in range(0,HEIGTH_VALUE):
        for colCount in range(0,WIDTH_VALUE):
            if(viewList[rowCount][colCount] == 2048):
                WinFlag = 1

init()
display()

while(1):
    opflg = 0
    op = input("上下左右移动:")
    if op in ['a', 'A']:    # 向左移动
        opflg = 1
        for row in range(0,WIDTH_VALUE):  
            control(view[row], 'left')
            
    elif op in ['d', 'D']:  # 向右移动
        opflg = 2
        for row in range(0,WIDTH_VALUE):  
            control(view[row], 'right')
            
    elif op in ['w', 'W']:  # 向上移动  
        opflg = 3
        
#view table x,y exchange
        for row in range(0,WIDTH_VALUE):
                for col in range(0, HEIGTH_VALUE):
                        exchange[row][col] = view[col][row]
        #left move
        for row in range(0,WIDTH_VALUE):  
            control(exchange[row], 'left')
        #view table x,y exchange
        for row in range(0,WIDTH_VALUE):
                for col in range(0, HEIGTH_VALUE):
                        view[row][col] = exchange[col][row]
                        
    elif op in ['s', 'S']:  # 向下移动  
        opflg = 4
        
#view table x,y exchange
        for row in range(0,WIDTH_VALUE):
                for col in range(0, HEIGTH_VALUE):
                        exchange[row][col] = view[col][row]
        #left move
        for row in range(0,WIDTH_VALUE):  
            control(exchange[row], 'right')
        #view table x,y exchange
        for row in range(0,WIDTH_VALUE):
                for col in range(0, HEIGTH_VALUE):
                        view[row][col] = exchange[col][row]

    else:
        print("[W, S, A, D]")

    isFinsh(view)
    
    if(WinFlag > 0):
        print("游戏胜利")
        break

    if(opflg > 0):
        ret = gene(view)
        if(ret == 0):
            display()
        else:
            print("游戏已经结束")
            break
